import {Directive, ElementRef, OnInit} from '@angular/core';
import {ActivatedRoute} from '@angular/router';
import {MenuJumpParam} from "@shared/model/erupt-menu";

@Directive({selector: '[buildTabParam]'})
export class BuildTabParamDirective implements OnInit {
    constructor(private elementRef: ElementRef, private activatedRoute: ActivatedRoute) {
    }

    ngOnInit(): void {
        setTimeout(() => { // wait for DOM rendering
            this.build();
        });
    }

    build(): void {
        const eles = <HTMLIFrameElement[]>this.elementRef.nativeElement.getElementsByTagName('iframe');
        for (let i = 0; i < eles.length; i++) {
            const iframe = eles[i];
            let src = iframe.src;
            //判断url中是否存在动态参数
            //console.log('指令得到iframe的url：' + src)
            if (src.indexOf('=${') != -1) {
                let paramKey: string = '';
                this.activatedRoute.queryParams.subscribe(param => {
                    paramKey = param[(MenuJumpParam.paramName)] || '';
                });
                if (paramKey === '') {
                    console.warn('从当前route中没有获取到[' + MenuJumpParam.paramName + ']的参数值，尝试从最顶层location[' + (top.window.location.href) + ']中获取...')
                    let tmps = top.window.location.href.split('?');
                    if (tmps && tmps.length > 1) {
                        tmps[1].split('&').forEach(kv => {
                            let kvs = kv.split('=');
                            if (kvs.length === 2) {
                                if (kvs[0] === MenuJumpParam.paramName) {
                                    paramKey = kvs[1];
                                }
                            }
                        })
                    }
                }
                if (paramKey === '') {
                    console.warn('从当前route中没有获取到[' + MenuJumpParam.paramName + ']的参数值，尝试从最顶层location的矩阵参数中获取...')
                    let tmps = top.window.location.href.split(';');
                    if (tmps && tmps.length > 1) {
                        tmps.shift();
                        tmps.forEach(kv => {
                            if (kv) {
                                let kvs = kv.split('=');
                                if (kvs.length === 2) {
                                    if (kvs[0] === MenuJumpParam.paramName) {
                                        paramKey = kvs[1];
                                    }
                                }
                            }
                        })
                    }
                }

                if (paramKey !== '' && src.indexOf('=${') > 0) {
                    const data = JSON.parse(window.sessionStorage.getItem(paramKey)) || {};
                    for (let k in data) {
                        src = src.replace(new RegExp('=\\${' + k + '}'), '=' + data[(k)]);
                    }
                }
            }

            let tData = localStorage.getItem('_token') || "{}";
            let token = JSON.parse(tData);

            iframe.src = src + (src.indexOf('?') > 0 ? '&' : '?') + '_token=' + (token.token || '');
        }
    }
}
